import {
  ForbiddenException,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { UserService } from '../user/user.service';
import { JwtService } from '@nestjs/jwt';
import * as crypto from 'crypto';

@Injectable()
export class AuthService {
  constructor(
    private userService: UserService,
    private jwtService: JwtService,
  ) {}
  // 登录
  async signIn(username: string, password: string) {
    const hash = crypto.createHash('md5');
    const user = await this.userService.findOne(null, username);
    if (!user) {
      throw new ForbiddenException('请先注册');
    }
    const hashPsd = hash.update(password).digest('hex');
    console.log(hashPsd);
    console.log(user);
    if (user.password !== hashPsd) {
      throw new UnauthorizedException('账户或密码不对');
    }
    const token = await this.jwtService.signAsync({
      username: username,
      userId: user.id,
    });
    return {
      token,
      userId: user.id,
    };
  }
  // 注册
  async signUp(body) {
    const { username } = body;
    const user = await this.userService.findOne(null, username);
    if (user) {
      throw new ForbiddenException('当前用户已注册');
    }
    return this.userService.create(body);
  }
}
